package com.trytotry.mybatis.generator.plugin;

import com.trytotry.mybatis.generator.util.FieldUtil;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.util.List;

/**
 * Created by tryer on 2016/10/13.
 */
public class ModelEqualsPlugin extends PluginAdapter {
    private final static String DELIMITER = ",";
    private final static String EQUAL_VALUE = "equalsValue";

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        String equalValue = introspectedTable.getTableConfigurationProperty(EQUAL_VALUE);
        if (equalValue != null && !"".equals(equalValue)) {
            topLevelClass.addMethod(addEqualsMethod(introspectedTable, equalValue.split(DELIMITER)));
        }
        return true;
    }

    private Method addEqualsMethod(IntrospectedTable introspectedTable, String[] equalValues) {
        String mName = "equals";
        FullyQualifiedJavaType paramType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        FullyQualifiedJavaType returnType = FullyQualifiedJavaType.getBooleanPrimitiveInstance();
        Method method = new Method();
        method.setName(mName);
        method.setVisibility(JavaVisibility.PUBLIC);
        //入参
        method.addParameter(new Parameter(paramType, "obj"));
        //返回true or false
        method.setReturnType(FullyQualifiedJavaType.getBooleanPrimitiveInstance());
        for (String str : equalValues) {
            String code = "" +
                    "if(!this." + str + ".equals(obj." + str + "))" +
                    "{return false;}";
            method.addBodyLine(code);
        }
        method.addBodyLine("return true;");
        return method;
    }
}
